﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.PersistenceObject.Business;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System;
using WMS.FC.Domain.Service.Technology.Interface;

namespace WMS.FC.Domain.Service.Technology
{
    public class DeleteTechnologyRouteService : ServiceBase, IDeleteTechnologyRouteService
    {
        protected readonly ITechnologyRepository technologyRepository;

        public DeleteTechnologyRouteService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ITechnologyRepository technologyRepository)
            : base(logger, options, mapper)
        {
            this.technologyRepository = technologyRepository;
        }

        public async Task<ActionResultBase> DeleteTechnologyRoute(List<string> selectedIds, UserInfo userInfo)
        {
            var result = new ActionResultBase("删除工艺路径");
            try
            {
                if (selectedIds == null || selectedIds.Count == 0)
                    return result.ArgumentError("请选择要删除的工艺路径");

                var technologyRouteId = Convert.ToInt64(selectedIds[0]);
                var technologyRoutePO = await technologyRepository.FindById<TechnologyRoutePO>(technologyRouteId);
                if (technologyRoutePO != null)
                {
                    var count = await technologyRepository.GetCount<CellPO>(entity => entity.TechnologyRouteCode == technologyRoutePO.Code);
                    if (count > 0)
                        return result.BusinessError($"工艺路径:{technologyRoutePO.Code},存在在制的电池,不能删除");

                    count = await technologyRepository.Delete<TechnologyRoutePO>(technologyRouteId);
                    if (count == 0)
                        return result.DbError("删除数据异常");

                    count = await technologyRepository.Delete<TechnologyRouteProcessPO>(entity => entity.TechnologyRouteCode == technologyRoutePO.Code);
                }

                result.Message = "删除数据成功";
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
